package com.wlcb.jpower.chat.controller.wx.mp;

import com.github.pagehelper.PageInfo;
import com.wlcb.jpower.chat.entity.wxuser.WxUserInfo;
import com.wlcb.jpower.chat.service.wx.mp.MessageTemplate;
import com.wlcb.jpower.chat.service.wx.mp.SendTemplateMsgEntity;
import com.wlcb.jpower.chat.service.wx.mp.TemplateMsgService;
import com.wlcb.jpower.chat.service.wxuser.WxUserInfoService;
import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.page.PaginationContext;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import com.wlcb.jpower.utils.WxMpInstance;
import com.wlcb.jpower.wx.mp.template.WxTemplateRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.tag.WxTagListUser;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/3/23 14:26
 * @desc: 微信用户管理
 */
@Api(tags = "微信用户管理")
@RestController
@RequestMapping("mpUser")
@RequiredArgsConstructor
public class WxMpUserController extends BaseController {

    private final MessageTemplate messageTemplate;
    private final TemplateMsgService templateMsgService;
    private final WxUserInfoService wxUserInfoService;

    @ApiOperation("查询微信用户")
    @GetMapping("list")
    public ResponseData<PageInfo<WxUserInfo>> userDbList(WxUserInfo wxUserInfo) {
        PaginationContext.startPage();
        List<WxUserInfo> pageList = wxUserInfoService.findPageList(wxUserInfo);
        return ReturnJsonUtil.ok("操作成功", new PageInfo<>(pageList));
    }
    /**
     * 根据openid获取用户信息 微信接口
     *
     * @param appId
     * @param openid
     * @return
     */
    @ApiOperation("根据openid获取用户信息")
    @GetMapping("userInfo")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<WxMpUser> userInfo(@ApiParam("公众号ID") String appId,@ApiParam("用户openid") String openid) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(openid,JpowerError.Arg,"用户openid不可为空");
        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        WxMpUser wxMpUser = wxMp.getUserService().userInfo(openid);
        return ReturnJsonUtil.ok("操作成功", wxMpUser);
    }

    /**
     * openid字符串 用,隔开 获取用户信息列表 微信接口
     *
     * @param appId
     * @param openids
     * @return
     */
    @ApiOperation("获取用户信息列表")
    @GetMapping("userInfoList")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<List<WxMpUser>> userInfoList(@ApiParam("公众号ID") String appId,@ApiParam("用户openid 多个逗号分隔") String openids) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(openids,JpowerError.Arg,"openids不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        List<WxMpUser> wxMpUsers = wxMp.getUserService().userInfoList(Fc.toStrList(openids));
        return ReturnJsonUtil.ok("操作成功", wxMpUsers);
    }

    /**
     * 根据 用户nextopenid 获取openid列表 微信接口
     *
     * @param appId
     * @param nextOpenid
     * @return
     */
    @ApiOperation("根据 用户nextopenid 获取openid列表")
    @GetMapping("/userList")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<WxMpUserList> userList(@ApiParam(value = "公众号ID",required = true) String appId,@ApiParam(value = "第一个拉取的OPENID，null为从头开始拉取",required = false) String nextOpenid) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        WxMpUserList wxMpUserList = wxMp.getUserService().userList(nextOpenid);
        return ReturnJsonUtil.ok("操作成功", wxMpUserList);
    }

    /**
     * 创建标签 微信接口
     *
     * @param appId
     * @param name
     * @return
     */
    @ApiOperation("创建标签")
    @PostMapping("/createTag")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<WxUserTag> createTag(@ApiParam(value = "公众号ID",required = true) String appId,@ApiParam(value = "标签名字",required = true) String name) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(name,JpowerError.Arg,"标签名字不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        WxUserTag tag = wxMp.getUserTagService().tagCreate(name);
        return ReturnJsonUtil.ok("操作成功", tag);
    }

    /**
     * 删除标签 微信接口
     *
     * @param appId
     * @param id
     * @return
     */
    @ApiOperation("删除标签")
    @PostMapping("/deleteTag")
    @SneakyThrows(WxErrorException.class)
    public ResponseData deleteTag(@ApiParam(value = "公众号ID",required = true) String appId,@ApiParam(value = "标签ID",required = true) Long id) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notNull(id,JpowerError.Arg,"标签ID不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        return ReturnJsonUtil.status(wxMp.getUserTagService().tagDelete(id));
    }

    /**
     * 修改标签 微信接口
     *
     * @param appId
     * @param id
     * @param name
     * @return
     */
    @ApiOperation("修改标签")
    @PostMapping("/updateTag")
    @SneakyThrows(WxErrorException.class)
    public ResponseData updateTag(@ApiParam(value = "公众号ID",required = true) String appId,
                                  @ApiParam(value = "标签ID",required = true) Long id,
                                  @ApiParam(value = "标签名字",required = true) String name) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notNull(id,JpowerError.Arg,"标签ID不可为空");
        JpowerAssert.notEmpty(name,JpowerError.Arg,"标签名字不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        return ReturnJsonUtil.status(wxMp.getUserTagService().tagUpdate(id, name));
    }

    /**
     * 获取标签列表 微信接口
     *
     * @param appId
     * @return
     */
    @ApiOperation("获取标签列表")
    @GetMapping("/getTagList")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<List<WxUserTag>> getTagList(@ApiParam(value = "公众号ID",required = true) String appId) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        List<WxUserTag> wxUserTags = wxMp.getUserTagService().tagGet();
        return ReturnJsonUtil.ok("操作成功", wxUserTags);
    }

    /**
     * 批量给用户打标签
     *
     * @param appId
     * @param openids
     * @param id
     * @return
     */
    @ApiOperation("批量给用户打标签")
    @PostMapping("/setUserTag")
    @SneakyThrows(WxErrorException.class)
    public ResponseData setUserTag(@ApiParam(value = "公众号ID",required = true) String appId,
                                   @ApiParam(value = "用户openid 多个逗号分隔",required = true) String openids,
                                   @ApiParam(value = "标签id",required = true) Long id) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(openids,JpowerError.Arg,"用户openid不可为空");
        JpowerAssert.notNull(id,JpowerError.Arg,"标签id不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }

        return ReturnJsonUtil.status(wxMp.getUserTagService().batchTagging(id, Fc.toStrArray(openids)));
    }

    /**
     * 批量删除用户标签
     *
     * @param appId
     * @param openids
     * @param id
     * @return
     */
    @ApiOperation("批量删除用户标签")
    @PostMapping("/deleteUserTag")
    @SneakyThrows(WxErrorException.class)
    public ResponseData deleteUserTag(@ApiParam(value = "公众号ID",required = true) String appId,
                                      @ApiParam(value = "用户openid 多个逗号分隔",required = true) String openids,
                                      @ApiParam(value = "标签id",required = true) Long id) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(openids,JpowerError.Arg,"用户openid不可为空");
        JpowerAssert.notNull(id,JpowerError.Arg,"标签id不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        return ReturnJsonUtil.status(wxMp.getUserTagService().batchUntagging(id, Fc.toStrArray(openids)));
    }

    /**
     * 获取标签下的用户
     *
     * @param appId
     * @param id
     * @param nextOpenid
     * @return
     */
    @ApiOperation("获取标签下的用户")
    @GetMapping("/getTagUser")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<WxTagListUser> getTagUser(@ApiParam(value = "公众号ID",required = true) String appId,
                                   @ApiParam(value = "标签id",required = true) Long id,
                                   @ApiParam(value = "第一个拉取的OPENID，null为从头开始拉取",required = false)  String nextOpenid) {
        JpowerAssert.notEmpty(appId,JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notNull(id,JpowerError.Arg,"标签id不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(appId)) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + appId);
        }
        WxTagListUser listUser = wxMp.getUserTagService().tagListUser(id, nextOpenid);
        return ReturnJsonUtil.ok("操作成功", listUser);
    }

    @ApiOperation("通过标签ID发送模板消息")
    @PostMapping("/sendMsgByTagId")
    @SneakyThrows(WxErrorException.class)
    public ResponseData sendMsgByTagId(SendTemplateMsgEntity entity) {
        JpowerAssert.notEmpty(entity.getAppId(), JpowerError.Arg,"appId不可为空");
        JpowerAssert.notEmpty(entity.getFirst(), JpowerError.Arg,"first不可为空");
        JpowerAssert.notEmpty(entity.getRemark(), JpowerError.Arg,"remark不可为空");
        JpowerAssert.notNull(entity.getTagId(), JpowerError.Arg,"tagId不可为空");
        JpowerAssert.notNull(entity.getParamCount(), JpowerError.Arg,"paramCount不可为空");
        JpowerAssert.notEmpty(entity.getTemplateId(), JpowerError.Arg,"templateId不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(entity.getAppId())) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + entity.getAppId());
        }
        WxTagListUser listUser = wxMp.getUserTagService().tagListUser(entity.getTagId(), entity.getNextOpenid());
        List<String> openidList = listUser.getData().getOpenidList();
        WxTemplateRequest template = messageTemplate.createTemplate(entity);
        if (template == null) {
            return ReturnJsonUtil.fail("paramCount与keyword数量不一致");
        }
        template.setToUsers(openidList);
        int i = templateMsgService.templateSend(template, true);
        if (openidList.size() == i) {
            return ReturnJsonUtil.ok("发送成功");
        }
        return ReturnJsonUtil.fail("发送失败", "发送总数：" + openidList.size() + "\n成功数量：" + i);
    }

    @ApiOperation("通过openId发送模板消息")
    @PostMapping("/sendMsgByOpenId")
    public ResponseData sendMsgByOpenId(SendTemplateMsgEntity entity) {
        JpowerAssert.notEmpty(entity.getAppId(), JpowerError.Arg,"appId不可为空");
        JpowerAssert.notEmpty(entity.getFirst(), JpowerError.Arg,"first不可为空");
        JpowerAssert.notEmpty(entity.getRemark(), JpowerError.Arg,"remark不可为空");
        JpowerAssert.notNull(entity.getParamCount(), JpowerError.Arg,"paramCount不可为空");
        JpowerAssert.notEmpty(entity.getTemplateId(), JpowerError.Arg,"templateId不可为空");

        WxMpService wxMp = WxMpInstance.getWxMp();
        if (!wxMp.switchover(entity.getAppId())) {
            return ReturnJsonUtil.fail("没有找到对应的公众号配置信息：" + entity.getAppId());
        }
        List<String> openidList = Fc.toStrList(entity.getSendUser());
        JpowerAssert.notEmpty(openidList, JpowerError.Arg,"sendUser不可为空");
        WxTemplateRequest template = messageTemplate.createTemplate(entity);
        if (Fc.isNull(template)) {
            return ReturnJsonUtil.fail("paramCount与keyword数量不一致");
        }
        template.setToUsers(openidList);
        int i = templateMsgService.templateSend(template, true);
        if (openidList.size() == i) {
            return ReturnJsonUtil.ok("发送成功");
        }
        return ReturnJsonUtil.fail("发送失败", "发送总数：" + openidList.size() + "\n成功数量：" + i);
    }
}
